<template>
  <div>
    <h3>登录</h3>
    <el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" :rules="rules" label-width="auto"
      class="demo-ruleForm" :size="formSize" status-icon>
      <!-- 用户名 -->
      <el-form-item label="用户名" prop="username">
        <el-input v-model="ruleForm.username" />
      </el-form-item>
      <!-- 密码 -->
      <el-form-item label="密码" prop="password">
        <el-input v-model="ruleForm.password" />
      </el-form-item>
      <!-- 登录按钮 -->
      <el-form-item>
        <el-button type="primary" @click="submitForm(ruleFormRef)">
          立即登录
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
// 导入创建响应式
import { reactive, ref } from 'vue'
// 导入封装好的aixos
import api from '../../api/api'
// 导入路由
import { useRouter } from 'vue-router'
// 创建路由实例
const router = useRouter()
// 创建响应式数据
const ruleFormRef = ref()
const ruleForm = reactive({
  username: '',
  password: ''
})
// 表单校验规则
const rules = reactive({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 10, message: '正确的长度为3~6位', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 3, max: 10, message: '正确的长度为3~6位', trigger: 'blur' },
  ],
})
// 登录按钮
const submitForm = async (formEl) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      api.post('/login', { username: ruleForm.username, password: ruleForm.password }).then(res => {
        console.log('登录请求', res)
        if (res.data.code === 10000) {
          router.push({ path: "/home" })
        }
      })
    } else {
      console.log('error submit!', fields)
    }
  })
}
</script>

<style lang="scss" scoped></style>